package com.gg.user.gguser.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.gg.header.getHeaderUser;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.Instant;

@Component
@Slf4j
public class LogoInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogoInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String ip = request.getRemoteAddr();
            Instant startTime = Instant.now();
            request.setAttribute("logrequestStartTime", startTime);
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取用户token
            Method method = handlerMethod.getMethod();
            LOGGER.info("用户:"+ip+",访问目标:"+method.getDeclaringClass().getName() + "." + method.getName());
        }catch (Exception e){

        }

        /**
         * 通过HttpServletRequest和HttpServletResponse做相应数据处理
         */
        String cookiceUser = getHeaderUser.getHader(response,request,"gg");
        if(cookiceUser != null){
            String ggId= JSONObject.parseObject(cookiceUser).getString("ggId");
            System.out.println("000000001:=========:"+ggId);
            return true;
        }else {
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("000000002");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("000000003");
    }


}
